package com.jcnet.bizaia.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jcnet.bizaia.App;
import com.jcnet.bizaia.R;
import com.jcnet.bizaia.adapter.VodTalkAdapter;
import com.jcnet.bizaia.bean.MainVodBean;
import com.jcnet.bizaia.bean.StateBean;
import com.jcnet.bizaia.bean.VodDetailBean;
import com.jcnet.bizaia.bean.VodDetailTalkBean;
import com.jcnet.bizaia.inter_face.OnClickFullScreenListener;
import com.jcnet.bizaia.tools.JCTools;
import com.jcnet.bizaia.tools.Toolkit;
import com.jcnet.bizaia.view.ProgressHUD;
import com.jcnet.bizaia.xstream.ACache;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;


@SuppressLint("ValidFragment")
public class VodDetalFragment extends SherlockFragment implements OnItemClickListener ,OnClickFullScreenListener{

	private List<VodDetailTalkBean> mainInfoBeans;

	private List<VodDetailTalkBean>tempInfoBeans;

	private PullToRefreshListView listView;

	private ListView simpleListView ;

	private View bottomView;  //底部加载更多按钮

	private View headViewPageView;

	//private View emptyView;     //数据为空

	private View noNetWorkView;  //没有网络\


	private View firstLodingView;  //没有网络\

	private VodTalkAdapter infoAdapter;

	private int nowPageSize = 1;

	private ACache aCache;

	private String HTTP_REQUEST =  App.HTTP_PATH+"vdo_showVideosOne.action?";

	private RequestParams params;

	private int allPapeSize;


	public static final String DISCUSSIONINFOFRAGMENT_STRING = "DISCUSSIONINFOFRAGMENT_STRING" ;


	private  TextView vodInfoTextView ;

	private EditText talkEditText;

	private ImageView userImgView;

	private Button commitButton;


	private VodDetailBean vodDetailBean;


	private ProgressHUD progressHUD;


	private String talkContent;
	
	
	private int vodID;
	
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		aCache = ACache.get(getActivity());

		params = new RequestParams();

		View view = View.inflate(getActivity(), R.layout.comm_list_onrefresh_with_vod_control,null);


		bottomView = View.inflate(getActivity(), R.layout.comm_foot_view, null);

		firstLodingView = View.inflate(getActivity(), R.layout.init_locad_view, null);

		headViewPageView = View.inflate(getActivity(), R.layout.vod_head_sub_lay, null);


		///////////////////////
		vodInfoTextView = (TextView) headViewPageView.findViewById(R.id.vodInfo);

		talkEditText = (EditText)headViewPageView.findViewById(R.id.talkContent);

		userImgView = (ImageView)headViewPageView.findViewById(R.id.talk_img);

		commitButton = (Button)headViewPageView.findViewById(R.id.commitTalk);



		commitButton.setOnClickListener(new OnClickListener() {    //提交评论

			@Override
			public void onClick(View v) {

				talkContent = talkEditText.getText().toString();

				if(Toolkit.isAvaliable(getActivity())){

					if(!TextUtils.isEmpty(talkContent.trim())){


						// TODO Auto-generated method stub
						/**
						 * 参数名称	参数类型	说明
							useridNum	int	用户编号
							didNum	int	评论对象ID
							loveNum	int	评论心情（1：喜欢2：一般3：讨厌）
							ctypeNum	int	评论类型（1：视频2：音频）
							content	string	评论内容
						 */
						RequestParams params = new RequestParams();
						params.put("useridNum", JCTools.getUserID(getActivity())+"");  
						params.put("didNum", vodID+"");
						params.put("loveNum", "2");
						params.put("ctypeNum", "1");
						params.put("content", talkContent);

						new AsyncHttpClient().post(App.HTTP_PATH+"comts_addComments.action?", params, new AsyncHttpResponseHandler(){
							@Override
							public void onStart() {
								// TODO Auto-generated method stub
								progressHUD = ProgressHUD.show(getActivity(), getActivity().getText(R.string.dataloding), false, true, null);
								super.onStart();
							}

							@Override
							public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
								// TODO Auto-generated method stub
								super.onSuccess(arg0, arg1, arg2);

								if(new String(arg2)!=null){
									StateBean stateBean = new Gson().fromJson(new String(arg2) , new TypeToken<StateBean>(){}.getType());
									if(stateBean.getState()==200){
										//评论成功
										talkContent = "";

										talkEditText.setText(talkContent);


										//刷新评论列表
										if(mainInfoBeans!=null){
											mainInfoBeans.clear();
										}
										nowPageSize = 1;
										sendHttp(nowPageSize);

									}else{
										//评论失败

										Toast.makeText(getActivity(), stateBean.getMessage(), 0).show();
									}
								}

							}

							@Override
							public void onFinish() {
								// TODO Auto-generated method stub
								super.onFinish();

								if(progressHUD.isShowing()){
									progressHUD.cancel();
								}
							}


							@Override
							public void onFailure(int arg0, Header[] arg1, byte[] arg2,
									Throwable arg3) {
								// TODO Auto-generated method stub
								super.onFailure(arg0, arg1, arg2, arg3);

								if(progressHUD.isShowing()){
									progressHUD.cancel();
								}
								Toast.makeText(getActivity(), getActivity().getText(R.string.serverError), 0).show();
							}
						});

					}else{
						Toast.makeText(getActivity(), "评论内容不能为空", 0).show();

					}

				}else{
					Toast.makeText(getActivity(), getActivity().getText(R.string.noNetWork), 0).show();

				}

			}
		});


		listView = (PullToRefreshListView)view.findViewById(R.id.commListViewWitheRefresh);


		//emptyView = View.inflate(getActivity(), R.layout.list_empty_no_data, null);

		noNetWorkView = View.inflate(getActivity(), R.layout.list_no_network, null);

		initListView();
		System.out.println("onCreateView__________________");


		return view;
	}

	
	public static VodDetalFragment newInstance() {
		VodDetalFragment fragment = new VodDetalFragment();
		return fragment;
	}


	public VodDetalFragment() {
		super();
		// TODO Auto-generated constructor stub
	}




	
	public void startHttp(MainVodBean vodBean){
		vodID = vodBean.getVid();
		
		if(mainInfoBeans!=null){
			mainInfoBeans.clear();
		}
		nowPageSize = 1;
		sendHttp(nowPageSize);
		simpleListView.addHeaderView(headViewPageView);
		
		System.out.println("开始请求视频详细");
	}



	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		if(isVisibleToUser){
			System.out.println("onCreateView__________________");
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	private void initListView() {
		// TODO Auto-generated method stub

		mainInfoBeans = new ArrayList<VodDetailTalkBean>();

		tempInfoBeans = new ArrayList<VodDetailTalkBean>();


		infoAdapter = new VodTalkAdapter(getActivity(), mainInfoBeans);


		listView.setOnItemClickListener(this);


		listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub   下拉刷新


				if(Toolkit.isAvaliable(getActivity())){
					if(mainInfoBeans!=null){
						mainInfoBeans.clear();
					}
					nowPageSize = 1;
					sendHttp(nowPageSize);
				}else{

					Toast.makeText(getActivity(), getString(R.string.noNetWork), 0).show();
					refreshView.onRefreshComplete();

				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub

			}
		});

		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				// TODO Auto-generated method stub


				if(nowPageSize==allPapeSize){
					bottomView.setVisibility(View.GONE);   //到达底部没有更多数据
					Toast.makeText(getActivity(), getString(R.string.noData), 0).show();
				}else{
					bottomView.setVisibility(View.VISIBLE);  //到达底部还有更多数据
					nowPageSize = nowPageSize+1;
					sendHttp(nowPageSize);
				}

			}
		});

		simpleListView = listView.getRefreshableView();
		
		simpleListView.setAdapter(infoAdapter);
		simpleListView.setOnItemClickListener(this);
		simpleListView.addFooterView(bottomView);
		


	}

	public void sendHttp(int page){


		System.out.println("超级赛亚人");
		/**
		 * @param
		 *  参数名称	参数类型	说明
			languageNum	int	语言种类：1：中文2：英文3：日文
			vidNum	int	动画id
			pageNum	int	当前第几页（默认第一页）——评论表
			pageSizeNum	int	当前分页显示条数（默认20条）——评论条数
		 */
		params.put("languageNum", App.localeCode+"");
		params.put("vidNum", vodID+"");          //	
		params.put("pageNum", page+"");
		//params.put("pageSizeNum",20);


		if(Toolkit.isAvaliable(getActivity())){

			new AsyncHttpClient().post(HTTP_REQUEST,params ,new AsyncHttpResponseHandler(){

				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();

				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub\
					
					super.onSuccess(arg0, arg1, arg2);
					
					System.out.println("视频详细:"+new String(arg2));

					if(new String(arg2)!=null){

						aCache.put(HTTP_REQUEST+params, new String(arg2),App.CACHE_TIME_DAY);
						setListData(new String(arg2));
					}


				}


				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					if(listView.isRefreshing()){
						listView.onRefreshComplete();
					}
					bottomView.setVisibility(View.GONE);


					if(vodDetailBean!=null){
						vodInfoTextView.setText(vodDetailBean.getContent().toString());

						Picasso.with(getActivity()).load(App.HTTP_PATH+JCTools.getUserBean(getActivity()).getUserimage()).centerCrop().resize(80	, 80).into(userImgView);//显示用户头像

					}
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					Toast.makeText(getActivity(), getString(R.string.serverError), 0).show();
					super.onFailure(arg0, arg1, arg2, arg3);
				}
			});
		}else{
			if(listView.isRefreshing()){
				listView.onRefreshComplete();
			}

			simpleListView.setEmptyView(noNetWorkView);


			firstLodingView.setVisibility(View.GONE);

			String requestString = aCache.getAsJSONObject(HTTP_REQUEST+params).toString();

			if(requestString!=null){

				setListData(requestString);
			}


			Toast.makeText(getActivity(), getString(R.string.noNetWork), 1).show();

		}
	}


	private void setListData(String arg2){



		String requestString = arg2;

		AllVoidDetial requestBeanRequest = new AllVoidDetial();


		//System.out.println("byte:"+new String(arg2));

		if(requestString!=null){



			System.out.println("requestString="+requestString);

			requestBeanRequest = new Gson().fromJson(requestString, new TypeToken<AllVoidDetial>(){}.getType());




			if(requestBeanRequest.getState()==200){
				allPapeSize = requestBeanRequest.getObjJson().getPagsum();
				firstLodingView.setVisibility(View.GONE);

				tempInfoBeans = null;

				vodDetailBean = requestBeanRequest.getObjJson();
				
				Intent intent = new Intent(JCVideoViewFragment2.JC_SETVOD_URL);
				intent.putExtra("vodDetailBean", vodDetailBean);
				getActivity().sendBroadcast(intent);

				tempInfoBeans = requestBeanRequest.getObjJson().getCommentsJson();

				if(!tempInfoBeans.isEmpty()||tempInfoBeans!=null){

					if(tempInfoBeans.isEmpty()||mainInfoBeans.size()<20){   //当本页的


						bottomView.setVisibility(View.GONE);

					}

					if(!tempInfoBeans.isEmpty()){

						mainInfoBeans.addAll(tempInfoBeans);

						infoAdapter.count = mainInfoBeans.size();

						infoAdapter.notifyDataSetChanged();
					}
				}


				//如果得到的内容总数为空的话显示没有数据的页面,同时隐藏foot界面
				if(mainInfoBeans.isEmpty()){
					//simpleListView.setEmptyView(emptyView);
					bottomView.setVisibility(View.GONE);
				}


			}else{
				Toast.makeText(getActivity(), requestBeanRequest.getMessage(), 0).show();
			}

			listView.onRefreshComplete();
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		/*Intent intent = new Intent(getActivity(), DiscussDetialActivity.class);
		intent.putExtra("imgUrl", mainInfoBeans.get(arg2).getPictureurl());
		startActivity(intent);*/
	}


	class AllVoidDetial {
		private int state;
		private String message;
		private  VodDetailBean objJson;
		public int getState() {
			return state;
		}
		public void setState(int state) {
			this.state = state;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public VodDetailBean getObjJson() {
			return objJson;
		}
		public void setObjJson(VodDetailBean objJson) {
			this.objJson = objJson;
		}

	}


	@Override
	public void onClick(ImageButton imageButton) {
		// TODO Auto-generated method stub

	}
}
